<script setup lang="ts">
import { ref, reactive } from 'vue'
import { getParticipantsAPI } from '@/services/room/room'
import { Socket } from 'socket.io-client'
import { useUserStore } from '@/stores'
import EmojiPicker from 'vue3-emoji-picker'
import { UploadFile } from 'element-plus'
const userStore = useUserStore()
import {
  ParticipantsResponseData,
  ParticipantsItem
} from '@/services/room/type'
import { onMounted } from 'vue'
import { watchEffect } from 'vue'

const account = ref('')

onMounted(async () => {
  // 获取用户信息
  userStore.getUserInfo().then(() => {
    account.value = userStore.userInfo.userInfo.username
  })
})
const { sock, roomId } = defineProps<{
  sock: Socket
  roomId: string
}>()

const getParticipantsData = async () => {
  const res: ParticipantsResponseData = await getParticipantsAPI(roomId)
  participants.value = res.data.participants
}
const participants = ref<ParticipantsItem[]>([])

/**
 * 表示一个用户，包括唯一标识符和账户名称。
 */
interface IUser {
  userId: string // 用户的唯一标识符
  account: string // 用户的账户名称
}

/**
 * 选择框下拉选项的结构定义。
 */
interface IOption {
  value: IUser | 'all' // 可以是一个用户对象或者'all'表示广播给所有用户
  label: string // 选项显示的标签
}

/**
 * 选择框选项数组的类型定义。
 */
type OptionsArray = IOption[]

// 反应性数据，用于存储选择框的选项
let selectOptions = reactive<OptionsArray>([{ value: 'all', label: '所有人' }])

sock.on('joined', async () => {
  await getParticipantsData()
  // 使用 map 创建一个新的对象数组，这个数组只包含 value 和 label 属性
  const newParticipantsOptions = participants.value
    .filter(item => account.value !== item.account)
    .map(item => ({
      value: { userId: item.userId, account: item.account }, // 确保 value 属性的结构和 IOption 接口一致
      label: item.account
    }))

  // 更新 selectOptions，不需要使用.value
  selectOptions.splice(
    1, // 从索引1开始删除
    selectOptions.length - 1, // 删除除第一个元素以外的所有元素
    ...newParticipantsOptions // 添加新的参与者选项
  )
  console.log(selectOptions)
})

/**
 * 发送消息的函数。
 * 根据选中的用户发送消息，若没有选择则显示警告。
 */
const sendMsg = (type?: string) => {
  console.log(selectUser.value)

  if (
    JSON.stringify(selectUser.value) === '{}' ||
    selectUser.value === undefined
  ) {
    ElMessage.warning('请选择发送的对象')
    return
  }

  // 根据选中的用户确定消息的类型
  const messageType = selectUser.value === 'all' ? 0 : 1
  // 创建接收者列表
  const recipientList = selectUser.value

  // 判断是图片还是文本
  let sendContent = ''
  type === 'img'
    ? (sendContent = dialogImgSrc.value)
    : (sendContent = submitMessage.value)

  // 向服务器发送消息
  sock.emit(
    'commentMsg',
    account.value,
    roomId,
    sendContent,
    messageType,
    recipientList
  )
  // 清空消息输入
  msg.value = ''
  // 关闭模态框
  dialogVisible.value = false
}
const msg = ref<string>('') // 用于存储输入消息的响应性引用
const submitMessage = ref<string>('') // 将发送给服务器的文本
const selectUser = ref<IUser | string>() // 用于存储选中发送用户的响应性引用
// 用于存储用户选择的表情编码
const emojiCodes = ref<string[]>([])
const selEmoji = ref<boolean>(false)

const openSelEmoji = () => {
  selEmoji.value = !selEmoji.value
}

interface EmojiResult {
  i: string // 表情图标的图像字符串
  n: string[] // 表情的名称数组
  r: string // 表情的 Unicode 编码，包含肤色
  t: string // 表情的肤色类型
  u: string // 表情的基本 Unicode 编码，不包含肤色
}

// 监听 msg 的变化，更新发送服务器的消息
watchEffect(() => {
  submitMessage.value = msg.value

  // 遍历存储的表情编码
  emojiCodes.value.forEach(code => {
    const emojiPlaceholder = `[${code}]`
    const emojiChar = String.fromCodePoint(parseInt(code, 16))
    submitMessage.value = submitMessage.value.replace(
      emojiChar,
      emojiPlaceholder
    )
  })
})

// 选择表情
const onSelectEmoji = (emoji: EmojiResult) => {
  // 更新 emojiCodes 数组
  emojiCodes.value.push(emoji.u)

  // 将表情字符添加到用户输入的消息中
  const emojiChar = String.fromCodePoint(parseInt(emoji.u, 16))
  msg.value += emojiChar

  openSelEmoji()
}

// 选择图片
const onSelectFile = (uploadFile: UploadFile) => {
  // 基于 FilerReader 的图片预览功能
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw!)
  reader.onload = () => {
    console.log(reader.result)
    dialogImgSrc.value = reader.result as string
    dialogVisible.value = true
  }
}

// 模态框显示状态
const dialogVisible = ref<boolean>(false)

// 模态框图片路径
const dialogImgSrc = ref()
</script>
<template>
  <div class="comment_send">
    <el-dialog
      v-model="dialogVisible"
      title="是否发送图片"
      width="30%"
      destroy-on-close
      center
      style="text-align: center"
    >
      <img
        :src="dialogImgSrc"
        alt=""
        style="width: 80%; margin: 0 auto; background-size: cover; height: 70%"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sendMsg('img')"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <div class="comment_send_tools">
      <div class="sendTools">
        <span>发送至</span>
        <el-select-v2
          v-model="selectUser"
          :options="selectOptions"
          placeholder="选择对象"
          style="width: 230px"
        />
      </div>
      <div class="selectTools">
        <div class="selectEmoji">
          <svg
            t="1699358097062"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="4914"
            width="22"
            height="22"
            @click="openSelEmoji"
          >
            <path
              d="M945.424922 509.059018c0-240.652965-195.076954-435.727873-435.726849-435.727873-240.651942 0-435.727873 195.074907-435.727873 435.727873 0 240.662175 195.075931 435.737082 435.727873 435.737082 98.792027 0 189.248202-33.611515 262.339894-88.998987 3.003404-3.40761 4.975315-7.753591 4.975315-12.637832 0-10.666944-8.651031-19.315928-19.315928-19.315928-5.53404 0-10.464329 2.194992-13.981433 5.91471l-0.246617 0c-65.407686 48.12916-145.915277 76.945463-233.346559 76.945463-217.908962 0-394.587893-176.701444-394.587893-394.598126 0-217.931474 176.678932-394.588917 394.587893-394.588917 217.930451 0 394.58687 176.657442 394.58687 394.588917 0 66.571185-15.617699 129.220037-44.74611 184.229908l0 0.323365c-0.536212 1.838881-1.122567 3.631714-1.122567 5.602601 0 10.666944 8.650007 19.315928 19.314904 19.315928 8.312316 0 15.259542-5.335519 17.971303-12.68388l0 0.1361C927.164023 649.080052 945.424922 581.210291 945.424922 509.059018zM395.534963 391.95902c0-24.334221-19.71911-44.052309-44.053332-44.052309-24.334221 0-44.052309 19.718087-44.052309 44.052309 0 24.334221 19.718087 44.029796 44.052309 44.029796C375.815853 435.989839 395.534963 416.294264 395.534963 391.95902zM669.125085 347.974249c-24.314779 0-44.030819 19.696598-44.030819 44.029796s19.717064 44.052309 44.030819 44.052309c24.332175 0 44.052309-19.71911 44.052309-44.052309C713.17637 367.669824 693.456237 347.974249 669.125085 347.974249zM680.214654 642.001843c-2.62171 0-5.063319 0.647753-7.370875 1.477654l-0.201591 0c-49.497321 22.382776-104.283088 34.728966-162.137751 34.728966-58.752102 0-114.322745-12.097526-164.423817-35.111682l-0.448208 0c-1.74576-0.468674-3.473101-1.095961-5.377474-1.095961-11.965519 0-21.621437 9.655917-21.621437 21.597901 0 7.912204 5.685489 15.400758 12.027941 19.173688-0.169869-0.075725-0.297782-0.132006 0.048095 0.028653 54.629201 24.670889 116.382661 39.593763 180.219571 39.593763 64.24214 0 124.875079-14.564717 179.772386-39.526225 6.721075-3.697205 11.293207-10.891048 11.293207-19.114336C701.994704 651.726322 692.224176 642.001843 680.214654 642.001843z"
              fill="#272636"
              p-id="4915"
            ></path>
          </svg>
          <EmojiPicker
            :native="true"
            @select="onSelectEmoji"
            :hide-search="true"
            :hide-group-icons="true"
            :disable-sticky-group-names="true"
            :disable-skin-tones="true"
            mode="append"
            :offset="10"
            v-if="selEmoji"
          />
        </div>
        <div class="selectImg">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onSelectFile"
          >
            <svg
              t="1699358150002"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="6881"
              width="22"
              height="22"
            >
              <path
                d="M870.4 128H153.6C102.4 128 64 166.4 64 217.6v588.8c0 51.2 38.4 89.6 89.6 89.6h716.8c51.2 0 89.6-38.4 89.6-89.6V217.6c0-51.2-38.4-89.6-89.6-89.6zM153.6 192h716.8c12.8 0 25.6 12.8 25.6 25.6v339.2l-185.6-140.8c-19.2-19.2-51.2-12.8-70.4 6.4l-204.8 192-102.4-121.6c-12.8-12.8-25.6-19.2-44.8-19.2-19.2 0-32 6.4-44.8 25.6L128 646.4V217.6c0-12.8 12.8-25.6 25.6-25.6zM128 806.4v-70.4l160-211.2h6.4l256 300.8H153.6c-12.8 6.4-25.6-6.4-25.6-19.2z m742.4 25.6h-256l-147.2-179.2 198.4-198.4h12.8L896 614.4v192c0 12.8-12.8 25.6-25.6 25.6z"
                fill="#333333"
                p-id="6882"
              ></path>
            </svg>
          </el-upload>
        </div>
      </div>
    </div>
    <div class="comment_send_msg">
      <textarea placeholder="请输入消息....." v-model="msg"></textarea>
    </div>
    <div class="comment_confirm">
      <el-button type="primary" @click="sendMsg('text')">发送</el-button>
    </div>
  </div>
</template>

<style scoped lang="less">
@import 'vue3-emoji-picker/css';
@import '../../../../assets/less/index.less';

:deep(.el-dialog__body) {
  text-align: center;
}
.comment_send {
  border-top: @border-grey;
  height: 30%;
  .comment_send_tools {
    padding: 5px 10px;
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    .selectTools {
      display: flex;
      align-items: center;
      .selectEmoji {
        cursor: pointer;
        position: relative;
        :deep(.v3-emoji-picker) {
          position: absolute;
          right: 0;
          bottom: 150%;
          height: 200px;
          overflow: auto;
          -ms-overflow-style: none; /* IE 和 Edge */
          scrollbar-width: none; /* Firefox */
        }
        :deep(.v3-emoji-picker) ::-webkit-scrollbar {
          display: none; /* Chrome, Safari */
        }
      }
      .selectImg {
        margin-left: 10px;
      }
    }
  }
  .comment_send_msg {
    margin: 8px 10px;
    height: 60%;
    width: 100%;
    textarea {
      display: block;
      border: none;
      outline: none;
      width: 100%;
      height: 100%;
      resize: none;
      font-size: 16px;
    }
  }
  .comment_confirm {
    margin: 5px 10px;
    position: relative;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
